import Vue from 'vue'
import axios from 'axios'
import Qs from 'qs'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// create an axios instance
const $axios = axios.create({
  baseURL: 'http://localhost', // 测试地址

  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

Vue.prototype.$axios = axios // 并发请求
// request interceptor
$axios.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
      // config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
$axios.interceptors.response.use(
  response => {
    // console.log(response, '登录用户的信息')
    // if (loading) {

    //   // this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
    //     loading.close();
    //   // });
    // }

    switch (response.data.code) {
      case 403:
        resetRouter()
        removeToken()
        router.push({
          path: '/login',
          query: {
            redirect: '/'
          }
        })
        Message.error('登录已过期，请重新登录')
        break
    //   case 413:
    //     if (router.history.current.name != 'sellerCertification') {
    //       router.replace({
    //         name: 'sellerCertification'
    //       })
    //       break
    //     }
    }
    // const res = response.data
    const code = response.status
    // console.log(response.data.data.token)
    if ((code >= 200 && code < 300) || code === 304) {
      // Message({
      //   message: response.data.msg,
      //   type: 'success',
      //   duration: 5 * 1000
      // })
      return Promise.resolve(response.data)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    // if (loading) {
    //   // loading.close()
    // }
    if (error.response) {
      // switch (error.response.status) {
      //
      //   case 403:
      //     // 返回401 清除token信息并跳转到登陆页面
      //     store.commit('DEL_TOKEN')
      //     router.replace({
      //       path: '/login',
      //       query: {
      //         redirect: router.currentRoute.fullPath
      //       }
      //     })
      //     break
      //   case 404:
      //     Message.error('网络请求不存在')
      //     break
      //   default:
      //     Message.error(error.response.data.message)
      // }
    } else {
      // 请求超时或者网络有问题
      if (error.message.includes('timeout')) {
        Message.error('请求超时！请检查网络是否正常')
      } else {
        Message.error('请求失败，请检查网络是否已连接')
      }
    }
    return Promise.reject(error)
  }
)

export default {
  post(url, data) {
    // console.log(data, 'upload')
    return $axios({
      method: 'post',
      url,
      data: Qs.stringify(data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  },
  get(url, params) {
    return $axios({
      method: 'get',
      url,
      params
    })
  },
  // 上传图片 取消qs
  updata(url, data) {
    return $axios({
      method: 'post',
      url,
      data,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  }
}
